/*
 * Copyright 2012 Faisal Aslam.
 * All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 * 
 * This code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * only, as published by the Free Software Foundation.
 * 
 * This code is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 3 for more details (a copy is
 * included in the LICENSE file that accompanied this code).
 * 
 * You should have received a copy of the GNU General Public License
 * version 3 along with this work; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 * 
 * Please contact Faisal Aslam (faisal.aslam AT gmail.com)
 * if you need additional information or have any questions.
 */
package takatuka.classreader.logic.parallel.addAttr;

import takatuka.classreader.dataObjs.MultiplePoolsFacade;
import takatuka.classreader.dataObjs.constantPool.UTF8Info;
import takatuka.classreader.logic.constants.TagValues;
import takatuka.classreader.logic.factory.FactoryFacade;
import takatuka.classreader.logic.factory.FactoryPlaceholder;
import takatuka.classreader.logic.util.Miscellaneous;

/**
 *
 *
 * @author Faisal Aslam
 */
class Util {

    private FactoryFacade factory =
            FactoryPlaceholder.getInstanceOf().getFactory();

    public int checkAndAddUTF8(String newName, MultiplePoolsFacade cp) {
        int index = getUTF8InfoIndex(newName, cp);
        if (index == -1) {
            index = addUTF8Info(newName, cp);
        }
        return index+1;
    }

    private final int addUTF8Info(String name, MultiplePoolsFacade cp) {
        try {
            UTF8Info utf8 = factory.createUTF8Info();
            byte[] data = name.getBytes();
            utf8.setBytes(factory.createUn(data));
            utf8.setLength(factory.createUn(data.length).trim(2));
            return cp.add(utf8, TagValues.CONSTANT_Utf8);
        } catch (Exception d) {
            d.printStackTrace();
            Miscellaneous.exit();
        }
        return -1;
    }

    final int getUTF8InfoIndex(String name, MultiplePoolsFacade cp) {
        int size = cp.getCurrentSize(TagValues.CONSTANT_Utf8);
        for (int loop = 1; loop < size; loop++) {
            Object obj = cp.get(loop, TagValues.CONSTANT_Utf8);
            if (obj instanceof UTF8Info) {
                UTF8Info utf8Info = (UTF8Info) obj;
                if (utf8Info.convertBytes().equals(name)) {
                    return loop;
                }
            }
        }
        return -1;
    }
    
   
}
